package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.ItemShop;
import cn.wolfcode.luowowo.article.mapper.ItemShopMapper;
import cn.wolfcode.luowowo.article.query.ItemShopQuery;
import cn.wolfcode.luowowo.article.service.IItemShopService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.domain.UserInfoScore;
import cn.wolfcode.luowowo.member.service.IUserInfoScoreService;
import cn.wolfcoe.luowowo.common.util.AjaxResult;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@Service
public class ItemShopServiceImpl implements IItemShopService {

    @Autowired
    private ItemShopMapper itemShopMapper;

    @Reference
    private IUserInfoScoreService userInfoScoreService;



    @Override
    public void saveOrUpdate(ItemShop itemShop) {
        if (itemShop.getId() == null) {
            itemShopMapper.insert(itemShop);
        }else {
            itemShopMapper.updateByPrimaryKey(itemShop);
        }

    }


    @Override
    public PageInfo query(ItemShopQuery qo) {
        PageHelper.startPage( qo.getCurrentPage(), qo.getPageSize() );
        return new PageInfo( itemShopMapper.selectForList( qo ) );
    }

    @Override
    public List<ItemShop> list() {
        return itemShopMapper.selectAll();
    }

    @Override
    public ItemShop get(Long id) {
        return itemShopMapper.selectByPrimaryKey(id);
    }

    @Override//减少商品数量
    public AjaxResult reduce(UserInfo userInfo, ItemShop itemShop) {
        //获取商品对象
        ItemShop shop = get(itemShop.getId());
        if (shop.getRest()==0) {
            return new AjaxResult(false,"很抱歉,商品已售罄");
        }
        UserInfoScore userInfoScore = userInfoScoreService.get(userInfo.getId());
        if (userInfoScore.getScore()<itemShop.getPrice().intValue()) {
            return new AjaxResult(false,"很抱歉,您的积分不足");
        }
        //减少商品数量
        shop.setRest(shop.getRest()-1);
        //更新数据库
        saveOrUpdate(shop);
        return AjaxResult.SUCCESS;
    }

}
